package com.cfweb.exception;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.cfweb.util.ExtJSResponse;

@Provider
@Component
public class ExceptionHandler implements ExceptionMapper<Throwable> {

	/**
*
*/
	private Logger logger = Logger.getLogger(this.getClass());

	/**
*
*/
	public Response toResponse(Throwable exception) {
		logger.error("exception:", exception);
		if(exception instanceof CloudFoundryApiException){
			ErrorBean bean=getErrorBeanFormCloudFoundryException(exception);
			return Response.status(400)
					.entity(ExtJSResponse.errorResWithDate(bean))
					.type(MediaType.APPLICATION_JSON).build();
		}

		ErrorBean bean=new ErrorBean(null,null,2);
		return Response.status(400)
				.entity(ExtJSResponse.errorResWithDate(bean))
				.type(MediaType.APPLICATION_JSON).build();
	}

	private ErrorBean getErrorBeanFormCloudFoundryException(Throwable exception) {
		CloudFoundryApiException ex=(CloudFoundryApiException) exception;
		logger.info(ex.getCause());
		logger.info(ex.getDescription());
		logger.info(ex.getErrorCode());
		return new ErrorBean(ex.getErrorCode(),ex.getDescription(),1);
	}

}